//GA omp
//$Id: ga_omp.h 441 2010-04-09 17:27:20Z Oleg.Bulychov $
#pragma once

#include "src/heo/include/easy_omp.h"
#include "src/heo/include/ring_coop.h"
#include "src/heo/include/xml_file.h"
#include "ga_common.h"

//__________________________________________________________________________________
/**
The Island Model with Ring Migration
*/
template<class T>
class GA_OMP:
    public GA<T>
{
public:
    typedef typename GA<T>::TEnvironment TEnvironment;
    typedef typename GA<T>::TSolution TSolution;

    typedef typename GA<T>::TDirection TDirection;
    typedef typename GA<T>::TCostType  TCostType;

protected:
    //TODO move to template arg?
    ring_cooperation<omp::recv, omp::isend, omp::isend> coop_;

public:
    template<class TInOutSolution>
    void solve(TInOutSolution& sol)
    {
        int np = omp_get_max_threads();
        omp::solver_fork< TInOutSolution, GA_OMP<T> > f(sol, *this);
        omp::communicator::run(np, f);
    }

    template<class V>
    void accept(V& v)
    {
        v(static_cast<GA<T>&>(*this), "/");
        v(VAR_(coop));
    }

    template<class TInOutSolution>
    void solve_OMP(Solution_Pool<TInOutSolution>& pool, omp::communicator& comm)
    {
        ASSERT_(this->rank_ == comm.rank());
        int np   = comm.size();
        int prev = (np + this->rank_ - 1) % np;
        int next = (this->rank_ + 1)      % np;

        this->init_From_Pool(pool);
        this->evaluate_Parents();
        this->update_Best_Fitness();
        this->calc_Max_Step();
        this->show_Progress(0);

        for (int step = 1; step <= this->max_step_; ++step)
        {
            this->select_Parents();

            this->apply_Intra_Operators(step);

            this->evaluate_Offsprings();

            this->select_Offsprings();

            this->update_Best_Fitness();

            //this->dump_Anytime_Solution(step);

            this->show_Progress(step);

            if (this->stop(step))
            {
                if (1 == np || !this->coop_.get_Rate())
                    break;//:no coop - no need for 'pending stop'
                this->pending_stop_ = 1;
            }

            if (this->coop_.cooperate(*this, this->rank_, prev, next, np, step, comm))
            {
                if (this->coop_.is_Async_Mode())
                {
                    if (this->sent_stop_)
                        break;
                }
                else
                {
                    volatile static long g_stop = 0;
                    if (this->pending_stop_)
                        g_stop = 1;
                    comm.barrier();
                    if (g_stop)
                        break;
                }
            }
        }

        //:this->evaluate_Parents();
        this->sort_Population();

        this->clear_OMP(comm);

        //this->dump_Anytime_Solution(-1);

        this->update_Pool(pool, comm);
    }

private:
    //void dump_Anytime_Solution(int nStep)//1-based
    //{
    //    if (!env_->anytime_rate_ || !env_->output_dir_.)
    //        return;

    //    if (nStep <= 0 || (nStep % env_->anytime_rate_ == 0))
    //    {
    //        std::cout << "** " << nStep << std::endl;
    //    }
    //}

    template<class TInOutSolution>
    void update_Pool(Solution_Pool<TInOutSolution>& pool, omp::communicator& comm)
    {
        if (0 == this->rank_)
        {
            pool.sol_list_.resize(this->output_size_);
            int j = 0;
            for (typename Solution_Pool<TInOutSolution>::iterator it = pool.sol_list_.begin();
                it != pool.sol_list_.end(); ++it, ++j)
            {
                it->init(this->env_, this->rnd_);
                it->assign(*(this->parent_[j]));
            }
        }
        comm.barrier();
#pragma omp critical
        {
            if (this->env_->debug_level_)
                std::cout << this->rank_ << ": cost = " << this->parent_[0]->get_Fitness() << lf;
            if (0 != this->rank_)
            {
                for (int j = 0; j < this->output_size_; ++j)
                {
                    TCostType fit = this->parent_[j]->get_Fitness();
                    for (typename Solution_Pool<TInOutSolution>::iterator it = pool.sol_list_.begin();
                        it != pool.sol_list_.end(); ++it)
                    {
                        if (TDirection()(fit, it->get_Cost()))
                        {
                            pool.sol_list_.insert(it, 1, *(this->parent_[j]));
                            pool.sol_list_.pop_back();
                            break;
                        }
                    }
                }
            }
        }
    }

    void clear_OMP(omp::communicator& comm)
    {
        comm.barrier();
        if (!coop_.is_Async_Mode())
            return;
        comm.clear_Data();
        comm.barrier();
    }
};
//__________________________________________________________________________________
//__________________________________________________________________________________

//EOF!
